<template>
    <div id="home">
        <div class="leftTop" v-if="!giveLessons" :class="[!giveLessons ? 'slowShow' : '']">
            <div class="radius"></div>
        </div>
        <courseware ref="courseware" v-if="isCoursewareShow"></courseware>
        <div v-if="isInformation" class="information flex-center">
            <information :isInformation="isInformation" @closeInformation="closeInformation"></information>
        </div>
    </div>
</template>

<script>
import information from './Information'
import courseware from './Courseware'
import user from '@/content/api/user'
import usermeta from '@/content/api/usermeta'
import store from '@/content/store/index.js'
import school from '@/content/api/school'
import resource from '@/content/api/resource'
import { SqlLib } from "../../../../../static/lib/sqlite/SqlLib";
import { SqlLibUser } from "../../../../../static/lib/sqlite/service/SqlLibUser";
import moment from 'moment'
import { User } from "../../../../../static/lib/sqlite/model/User";
import { Publisher } from "../../../../../static/lib/sqlite/model/Publisher";
import { Book } from "../../../../../static/lib/sqlite/model/Book";
import { DownloadCenter } from "../../../../../static/lib/downloader/DownloadCenter";
import { ThumbDownloader } from "../../../../../static/lib/downloader/ThumbDownloader";
import { getAppNewVersion } from '@/content/api/appversion'
import { UpdateApp } from '../../utils/UpdateApp'
import { Message } from '../../global/message/index'
import { updateLineStatus, contorlMessageCenter, updateUserMessage } from '../../utils/event'
import { SqlLibBook } from '../../../../../static/lib/sqlite/service/SqlLibBook'
import bus from '../../assets/js/bus'
import { mapState } from 'vuex'
const cryUtil = require('../../../../../static/utils/CrypUtil');
export default {
    name: "index",
    components: { information, courseware },
    provide () {
        return {
            refreshHomePage: this.refreshHomePage,
            initPersonStatus: this.initPersonStatus,
        }
    },
    data () {
        return {
            isInformation: false,
            color: false,
            isMax: false,
            isCoursewareShow: false,
            userName: '',
            offlineLogo: false,
            vipMember: "2",
            isSvip:false,
        }
    },
    mounted () {
        console.log("是否已经检测过网络？ ==> " + window.netStatus)
        console.log('route------------',this.$route);
        let _this = this;
        this.$nextTick(() => {
            _this.getUserSpace()
            _this.initVip()
            setTimeout(() => {
               if (!window.netStatus) {
                    this.$client.checkInternet(function (data) {
                        window.netStatus = true;
                        localStorage.isOffline = (data === 0);
                        if (data !== 0) {
                            _this.checkLogin(data);
                            setTimeout(() => {
                                _this.checkIsForcedUpdate(data)
                            }, 100);                           
                        } else {
                            _this.checkLogin(data);
                        }
                        require('../../global/timer/index')
                        // Message.getPostMessage();
                    })
                } else {
                    _this.initLessonInfo().then(res => {
                        console.log("else initLessonInfo ::> " + res);
                        _this.initPersonStatus()
                    });
                }
            }, 100);
        });
    },
    computed:{
        ...mapState(['giveLessons']),
    },
    methods: {
        getUserSpace(){
            resource.getUserSpace({
                appKey:'NOVO_EDU_BEAUTY_SCIENCE_PC'
            }).then( res =>{
                if (res.code == '0') {
                    localStorage.setItem('spaceSize',res.returnValue.totalSize)
                    if(res.returnValue.usedSize > res.returnValue.totalSize){
                        localStorage.setItem('spaceusedSize',res.returnValue.totalSize) 
                    }else{
                        localStorage.setItem('spaceusedSize',res.returnValue.usedSize) 
                    }
                }
            })
        },
        async initVip(){
            let _this = this;
            const sqlib = new SqlLib.getInstance(window.$DBDIR)
            const users = SqlLibUser.queryCurrentUser(sqlib)
            if (!users) {
                return
            }
            var VipType = ''
            VipType = cryUtil.aesDecrypt(users.vipType + "", users.id + "", true);
            VipType = new Buffer(VipType, 'base64').toString('utf8');
            console.log(VipType);
            if (VipType == '0') {
                _this.isSvip = true
            }else{
                _this.isSvip = false
            }
            if (VipType != '2') {
                store.state.becomeVip = true
            }
        },
        transitionend () {
            // this.messageCenterIsShow = !this.messageCenterIsShow
        },
        closeInformation (val) {
            this.isInformation = val
        },
        checkIsForcedUpdate () {
            let _this = this;
            if (localStorage.isSilent) {
                localStorage.removeItem('isSilent')
            }
            if (localStorage.isProductUpdate) {
                localStorage.removeItem('isProductUpdate')
            }
            let oldVersion = this.$readIniFile('data', 'ver')
            console.log(oldVersion);
            localStorage.setItem('oldVersion', oldVersion)
            getAppNewVersion({
                clientType: '1',
                currentVersion:oldVersion,
            }).then(res => {
                let data = res.returnValue
                if (res.code === '0') {
                    if (oldVersion < data.currentVersion) {
                        bus.$emit('set_versionData', JSON.stringify(data))
                        // localStorage.setItem('versionData',JSON.stringify(res.returnValue))
                    }
                    
                    const path = require('path')
                    console.log(data.isSilent);
                    let exePath = process.env.NODE_ENV === 'production' ? path.resolve(path.dirname(process.execPath), 'bos_updater.exe') : './bos_updater/bin/bos_updater'
                    let exeParmsArr = [data.url,  data.isGlobal === '0' ? '/e' : '/z', data.isSilent === '0' ? '' : '/s']
                    if (data.isSilent === '0') {
                        // if (data.currentVersion && oldVersion) {
                        //     oldVersion = parseInt(oldVersion);
                        //     if (data.currentVersion > oldVersion){
                        //         if (data.forceMinVersion && data.forceMaxVersion){
                        //             if (oldVersion >= data.forceMinVersion && oldVersion <= data.forceMaxVersion){
                        //                 UpdateApp.update(exePath, exeParmsArr, { message: data.description, version: data.currentVersion, close: false, cancel: '退出', }, true);
                        //                 return;
                        //             }
                        //         }
                        //     }
                        // }
                        if (_this.isSvip === false) { 
                            //不是svip
                            if (data.currentVersion && oldVersion){
                                oldVersion = parseInt(oldVersion);
                                if (data.currentVersion > oldVersion){
                                    if (data.forceMinVersion && data.forceMaxVersion){
                                        if (oldVersion >= data.forceMinVersion && oldVersion <= data.forceMaxVersion){
                                                UpdateApp.update(exePath, exeParmsArr, { message: data.description, version: data.currentVersion, close: false, cancel: '退出', }, true);
                                        }
                                    }
                                }
                            } 
                        }else{
                            if (data.currentVersion && oldVersion){
                                oldVersion = parseInt(oldVersion);
                                console.log(oldVersion);
                                if (data.currentVersion > oldVersion){
                                    if (data.forceMinVersion && data.forceMaxVersion){
                                        if (oldVersion >= data.forceMinVersion && oldVersion <= data.forceMaxVersion){
                                            UpdateApp.update(exePath, exeParmsArr, { message: data.description, version: data.currentVersion, close: false, cancel: '退出', }, true);
                                        }
                                    }else{
                                        UpdateApp.update(exePath, exeParmsArr, { message: data.description, version: data.currentVersion, close: false, cancel: '取消', }, false);
                                    }
                                }
                            } 
                        }
                    }
                    
                    if (data.isSilent === '1') {
                            localStorage.setItem('isSilent', JSON.stringify({ exePath: exePath, exeParmsArr: exeParmsArr, message: { message: data.description } }))
                    }
                }
                
            })
        },
        checkLogin (data) {
            let _this = this;
            console.log("isOffline ::>" + data)
            if (data !== 0) {//在线
                if (data === 1) {//代表是token过期
                    let version = this.$readIniFile("data", "versionInfo");
                    if (localStorage.refreshToken) {
                        user.switchToken({
                            refreshToken: localStorage.refreshToken,
                            currentVersion: version
                        }).then(response => {
                            if (response.code === "0") {
                                localStorage.setItem('accesstoken', response.returnValue.accessToken)
                                localStorage.setItem('refreshToken', response.returnValue.refreshToken)
                                _this.getUserInfo();
                            } else {
                                console.log("switchToken 失败...");
                                _this.$message.error(response.message);
                                localStorage.removeItem("isOffline");
                                localStorage.removeItem("accesstoken");
                                localStorage.removeItem("refreshToken");
                                _this.$router.push({ name: 'login' })
                            }
                        }).catch(error => {
                            console.error("error -> ", error);
                            console.log("switchToken 失败...");
                            _this.$message.error("网络异常！");
                            localStorage.removeItem("isOffline");
                            localStorage.removeItem("accesstoken");
                            localStorage.removeItem("refreshToken");
                            _this.$router.push({ name: 'login' })
                        })
                    } else {
                        console.log("没有refreshToken...");
                        _this.$router.push({ name: 'login' })
                    }
                } else {
                    _this.getUserInfo();
                }
            } else {//离线
                let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR));
                if (user) {
                    let offlineExpired = user.offlineExpired;
                    offlineExpired = cryUtil.aesDecrypt(offlineExpired, user.id, true);
                    offlineExpired = new Buffer(offlineExpired, 'base64').toString('utf8');
                    offlineExpired = parseInt(offlineExpired);
                    console.log("offlineExpired ::> " + offlineExpired);
                    if (offlineExpired && offlineExpired > 0) {
                        if (offlineExpired < 20) {
                            _this.$dialog({
                                confirm: '确认',
                                message: '您的离线使用权限即将过期，请尽快联网后重新登录！',
                                close: false,
                                type: "warn"
                            }).then(() => {
                                offlineExpired = offlineExpired - 1;
                                user.activeTime = moment().format('YYYY-MM-DD HH:mm:ss');
                                // !!!注意offlineExpired当前是int类型，需转成字符串后再加密，否则无法正常解密
                                user.offlineExpired = cryUtil.aesEncrypt(offlineExpired + "", user.id + "", true);
                                let result = SqlLib.getInstance(window.$DBDIR).updateObjectById(user);
                                _this.isCoursewareShow = true;
                                contorlMessageCenter()
                                _this.initPersonStatus();
                            })
                        } else {
                            offlineExpired = offlineExpired - 1;
                            user.activeTime = moment().format('YYYY-MM-DD HH:mm:ss');
                            user.offlineExpired = cryUtil.aesEncrypt(offlineExpired + "", user.id + "", true);
                            let result = SqlLib.getInstance(window.$DBDIR).updateObjectById(user);
                            _this.isCoursewareShow = true;
                            contorlMessageCenter()
                            _this.initPersonStatus();
                        }
                    } else {
                        _this.$message({
                            message: '您离线使用权限已过期，请联网重新登录！',
                            type: 'warning'
                        });
                        _this.$router.push({ name: 'login' });
                        return
                    }
                } else {
                    _this.$message({
                        message: '网络异常，请检查网络连接！',
                        type: 'warning'
                    });
                    _this.$router.push({ name: 'login' });
                }
            }
        },

        //获取用户信息
        getUserInfo () {
            let _this = this;
            let offlineUseTime = this.$readIniFile("data", "ofuTime");
            // console.log("offlineUseTime ::> " + offlineUseTime);
            user.getUserInfo().then(response => {
                if (response.code == "0") {
                    let resUser = response.returnValue;
                    bus.$emit('use-sign', resUser.sign === '1' ? false : true)
                    _this.userName = resUser.userBaseVO.fullName;
                    let user = new User();
                    user.id = resUser.userBaseVO.userId;
                    user.name = resUser.userBaseVO.fullName ? resUser.userBaseVO.fullName : "";
                    user.mobile = resUser.userBaseVO.mobile ? resUser.userBaseVO.mobile : "";
                    user.avatar = resUser.userBaseVO.avatar ? resUser.userBaseVO.avatar : "";
                    user.limitCount = resUser.userBaseVO.limitCount ? resUser.userBaseVO.limitCount : 1;
                    user.schoolName = resUser.schoolName ? resUser.schoolName : "";
                    user.schoolId = resUser.schoolId ? resUser.schoolId : "";
                    user.isGlobal = resUser.isGlobal ? resUser.isGlobal : "";
                    user.eduLevelId = resUser.eduLevelId ? resUser.eduLevelId : "";
                    user.vipType = cryUtil.aesEncrypt(resUser.isVip + "", user.id + "", true);
                    user.remainderDays = cryUtil.aesEncrypt(resUser.days + "", user.id + "", true);
                    user.activeTime = moment().format('YYYY-MM-DD HH:mm:ss');
                    user.offlineExpired = offlineUseTime ? offlineUseTime : _this.$CONST.global.offlineDefaultDays;
                    user.offlineExpired = cryUtil.aesEncrypt(user.offlineExpired + "", user.id + "", true);
                    user.reverse2 = resUser.userBaseVO.isConfigWhiteUser ? resUser.userBaseVO.isConfigWhiteUser : ''
                    //更新用户信息
                    let sqlInstance = SqlLib.getInstance(window.$DBDIR);
                    let result = sqlInstance.updateOrInsertObjectById(user);
                    if (sqlInstance.checkSqlError(result)) {
                        //初始化教材、书籍
                        _this.initLessonInfo().then(res => {
                            _this.initPersonStatus();
                            console.log("initLessonInfo ::> " + res);
                        });
                    } else {
                        _this.$message("用户信息保存失败")
                        _this.$router.push({ name: 'login' })
                    }
                } else {
                    _this.$message(response.message);
                    _this.$router.push({ name: 'login' })
                }
            }).catch(error => {
                _this.$message.error("用户信息获取异常")
                _this.$router.push({ name: 'login' })
            })
        },
        goPerson () {
            this.$router.push('/index/person')
        },
        async initLessonInfo () {
            let _this = this;
            let result = "";
            if (localStorage.isOffline && localStorage.isOffline == "false") {//在线
                let options = {
                    title: '正在加载中',
                    time: 15000,
                    progress: false,
                    full: true,
                }
                let loadingMask = _this.$downloadmask('#app', options)
                function allPublish () {
                    return new Promise((resolve, reject) => {
                        let promiseArry = [];
                        const globalEduL = _this.$CONST.global.eduLevel
                        const eduId = window.eduLevel === 'primary' ? [globalEduL.primary] : [globalEduL.junior, globalEduL.high]
                        school.getAllPublisher().then(publishes => {
                            if (publishes.code == "0") {
                                publishes = publishes.returnValue;
                                let tempPublishes = [];
                                publishes.forEach(publisher => {
                                    // TODO:暂时不知是否这样做判断等待后续修改
                                    if (publisher.eduLevelId && eduId.includes(publisher.eduLevelId)) {
                                        let tempPub = new Publisher();
                                        tempPub.id = publisher.id;
                                        tempPub.name = publisher.name;
                                        tempPub.reverse1 = publisher.type; //教材类信
                                        tempPub.eduLevelId = publisher.eduLevelId ? publisher.eduLevelId : '';
                                        tempPub.brief = publisher.brief ? publisher.brief : '';
                                        tempPub.version = publisher.version ? publisher.version : -1;
                                        tempPublishes.push(tempPub);
                                        // SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(tempPub);

                                        const params = {
                                            publisherId: tempPub.id
                                        }
                                        let bookPromise = new Promise((resolve1, reject1) => {
                                            school.getBooksByPublisherId(params).then(books => {
                                                let tempBooks = [];
                                                let tempThumbs = [];
                                                if (books.code == "0") {
                                                    books = books.returnValue;
                                                    books.forEach(book => {
                                                        let tempBook = new Book();
                                                        tempBook.id = book.id;
                                                        tempBook.name = book.name;
                                                        tempBook.publisherId = book.publisherId;
                                                        tempBook.brief = book.brief ? book.brief : '';
                                                        tempBook.authPeriod = book.authPeriod ? book.authPeriod : '';
                                                        tempBook.sortIndex = book.sortIndex ? book.sortIndex : -1;
                                                        if (book.thumb) {
                                                            let tempThumb = book.thumb;
                                                            tempThumb = tempThumb.match(/static.kquestions.com\/(\S*)\?/)[1];
                                                            tempBook.thumb = tempThumb;
                                                            tempThumbs.push(book.thumb);
                                                        }
                                                        tempBook.isAuthorize = book.isAuthorized ? book.isAuthorized : '';
                                                        tempBook.isAuthorize = cryUtil.aesEncrypt(tempBook.isAuthorize + "", tempBook.id + "", true);
                                                        tempBook.version = book.version ? book.version : '';
                                                        tempBooks.push(tempBook);
                                                        // SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(tempBook);
                                                    })
                                                }
                                                //异步去下载缩略图了
                                                ThumbDownloader.downloadPublisherThumbs(tempThumbs);
                                                resolve1(tempBooks);
                                            }).catch(error => {
                                                reject1("error");
                                            })
                                        });
                                        promiseArry.push(bookPromise);
                                    }
                                });
                                Promise.all(promiseArry).then(values => {
                                    let allBooks = [];
                                    values.forEach(value => {
                                        allBooks = allBooks.concat(value);
                                    });
                                    const sqlLib = SqlLib.getInstance(window.$DBDIR)
                                    const oldAllBooks = SqlLibBook.queryAllBooks(sqlLib)
                                    const oldAllPublishers = SqlLibBook.queryPublisher(sqlLib, eduId)
                                    let tempPublishesId = []
                                    let allBooksId = []
                                    tempPublishes.forEach(item => {
                                        tempPublishesId.push(item.id)
                                    })
                                    allBooks.forEach(item => {
                                        allBooksId.push(item.id)
                                    })
                                    oldAllPublishers && oldAllPublishers.forEach(item => {
                                        if (!tempPublishesId.includes(item.id)) {
                                            sqlLib.deleteObjectById(item)
                                        }
                                    })
                                    oldAllBooks && oldAllBooks.forEach(item => {
                                        if (!allBooksId.includes(item.id)) {
                                            sqlLib.deleteObjectById(item)
                                        }
                                    })
                                    sqlLib.updatePublishAndBook(tempPublishes, allBooks)
                                    resolve("success");
                                }).catch(error => {
                                    reject("error");
                                })
                            }
                        });
                    });
                }
                result = await allPublish();
                loadingMask.close()
            }
            _this.isCoursewareShow = true;
            contorlMessageCenter()
            return result;
        },
        initPersonStatus () {
            let sqlLib = SqlLib.getInstance(window.$DBDIR);
            let user = SqlLibUser.queryCurrentUser(sqlLib);
            this.userName = user.name ? user.name : ""
            this.vipMember = cryUtil.aesDecrypt(user.vipType, user.id, true);
            this.vipMember = new Buffer(this.vipMember, 'base64').toString('utf8');
            //是否需要注册
            this.isInformation = user.schoolId ? false : true;
            updateLineStatus((localStorage.isOffline && localStorage.isOffline === "true"));
            updateUserMessage();
            // this.offlineLogo = (localStorage.isOffline && localStorage.isOffline === "true");
        },
        refreshHomePage () {
            let _this = this;
            _this.initLessonInfo().then(res => {
                console.log("else initLessonInfo ::> " + res);
                _this.$refs.courseware.initPage();
                _this.initPersonStatus();
            });
        }
    }
}
</script>

<style lang="scss">
#home {
    height: 100%;
    .leftTop{
        position: absolute;
        left: 280px;
        top: 0;
        z-index: 9;
        height: 12px;
        width: 12px;
        border:none;
        background: linear-gradient(180deg, #A5D3FE 100%, #8EC6F9 100%);
        .radius{
            position: absolute;
            width: 12px;
            height: 12px;
            border-radius: 12px 0 0 0 ;
            background: #fff;
        }
    }
    .slowShow{
        animation: slowshow 0.7s linear 1;
    }
    @keyframes slowshow {
        0%{
            opacity: 0;
        }
        95%{
            opacity: 0;
        }
        100%{
          opacity: 1;
        }
    }
    .logo-user {
        // padding-left: 40px;
        // padding-top: 15px;
    }
    .logo-item {
        .main-logo {
            width: 323px;
            height: 36px;
        }
        .logo {
            width: 1px;
            height: 30px;
            border: 1px solid black;
            background-color: black;
            opacity: 0.3;
            border-radius: 8px;
        }
    }
    .user-item {
        .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background-color: #fff;
            overflow: hidden;
            display: inline-block;
            img {
                width: 36px;
                height: 36px;
                border-radius: 50%;
            }
        }
        .name {
            margin: 0 8px;
        }
        .member-level {
            img {
                width: 35px;
                height: 16px;
            }
        }
        .message {
            margin-left: 16px;
            margin-top: 2px;
            position: relative;
            .message-tips {
                position: absolute;
                width: 28px;
                height: 28px;
                color: #fff;
                line-height: 28px;
                text-align: center;
                top: -12px;
                right: -12px;
                font-size: 14px;
                transform: scale(0.5, 0.5);
                border-radius: 50%;
                background: #f56c6b;
            }
            img {
                width: 20px;
                height: 18px;
            }
            .message-center-container {
                position: absolute;
                right: 0;
                height: 735px;
                width: 360px;
                opacity: 1;
                z-index: 3333;
                top: 32px;
                overflow: hidden;
                transition: all 0.5s ease-in-out;
            }

            // .hidden-message-center {
            //     height: 0;
            //     width: 0;
            //     opacity: 0;
            // }
            .message-enter-active,
            .message-leave-active {
                transition: all 0.8s ease-in-out;
            }
            .message-enter,
            .message-leave-to {
                opacity: 0;
                height: 0;
                width: 0;
            }
        }
    }
    .information {
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        background: rgba(0, 0, 0, 0.7);
        z-index: 9999;
    }
}
</style>
